package com.ccp.dev.system.controller;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.*;
import com.ccp.dev.system.service.*;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
/**
 * 对象功能:发送消息 控制器类
 * 开发人员:csx
 * 创建时间:2019-07-24 15:10:58
 */
@Controller
@Action(ownermodel= SysAuditModelType.USER_MANAGEMENT)
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/messageSend")
public class MessageSendController extends SysBaseController {
    @Resource
    private MessageReceiverService receiverService;
    @Resource
    private MessageSendService sendService;
    @Resource
    private MessageReadService messageReadService;
    @Resource
    private MessageReplyService replyService;
    //是否删除 0有效  1已删除
    private static final int ISDELETE_FALSE = 0;

    /**
     * 查看本用户已发送信息分页列表（发送字段edit判断编辑按钮是否隐藏）
     * @param request
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="查看发送消息分页列表",detail="查看发送消息分页列表<#if success>成功<#else>失败</#if>",exectype = "查询日志")
    @ResponseBody
    public ResultData list(HttpServletRequest request) {
        //获取当前时间
        Date now = new Date();
        Long longTime = now.getTime();
        //设置定时器
        int spanTime = PropertyUtil.getIntByAlias("send.timeout", 200000);
        try {
            QueryFilter queryFilter = new QueryFilter(request);
            //获取当前用户ID
            String userId = ContextUtil.getCurrentUserId();
            queryFilter.addFilter("userId", userId);
            //设置过滤已删除信息数据
            queryFilter.addFilter("isDelete", ISDELETE_FALSE);
            List<MessageSend> list = sendService.queryList(queryFilter);
            //插入字段Edit用于页面判断是否显示消息编辑按钮
            for (MessageSend send : list) {
                //发送消息在3分钟之内可被再次编辑
                if (longTime - send.getSendTime().getTime() < spanTime) {
                    send.setEdit(MessageSend.CANEDIT);
                } else {
                    send.setEdit(MessageSend.NOTEDIT);
                }
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", queryFilter.getPageBean().getTotalCount(), list);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataSuccess("operation.failure");
        }
    }

    /**
     * 编辑发送信息页面信息详情
     * @param request
     * @return ResultData
     */
    @Action(description="编辑发送消息数据获取",
            detail="编辑发送消息数据获取<#if success>成功<#else>失败</#if>",exectype = "查询日志")
    @RequestMapping("/edit")
    @ResponseBody
    public ResultData editMessage(HttpServletRequest request) {
        String id = RequestUtil.getString(request, "messageId");
        try {
            MessageSend messageSend = sendService.getById(id);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", 0, messageSend);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 添加或更新发送消息并插入消息日志
     * @param messageSend 添加或更新的消息实体
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="添加或更新消息",
            detail="<#if StringUtil.isNotEmpty(id)>更新<#else>添加</#if>消息<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    public ResultData save(@RequestBody MessageSend messageSend)  {
        SysAuditThreadLocalHolder.putParamerter("id", messageSend.getId());
        messageSend.setJsonFile(StringEscapeUtils.unescapeHtml4(messageSend.getJsonFile()));
        try {
            SysUser curUser = (SysUser) ContextUtil.getCurrentUser();
            //获取当前人姓名、id、发送时间及设置逻辑删除字段
            messageSend.setSendTime(new Date());
            messageSend.setUserId(curUser.getUserId());
            messageSend.setUserName(curUser.getFullName());
            messageSend.setIsDelete(ISDELETE_FALSE);
            //设置日志操作字段
            Integer state = MessageLog.STATE_SUCCESS;
            //TODO 数据库事务问题
            sendService.addMessageSend(messageSend, curUser);
            //TODO 保存发送消息日志
            //TODO 获取server用@Resource注解
            MessageLogService messageLogService = AppUtil.getBean(MessageLogService.class);
            String tenantId = curUser.getTenantId();
            messageLogService.addMessageLog(messageSend.getSubject(), messageSend.getReceiverName(), MessageLog.INNER_TYPE, state, tenantId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("save.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("save.failure");
        }
    }

    /**
     * 删除发送消息
     * @param request
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description="删除发送信息",
            detail="删除发送信息<#if success>成功<#else>失败</#if>",
            exectype = "删除日志")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        try {
            String[] lAryId = RequestUtil.getStringAryByStr(request, "id");
            //删除操作需将接收消息表中的数据也进行删除
            sendService.deleteMessage(lAryId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 取得发送消息明细
     * @param request
     * @return ResultData
     * @throws Exception
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @Action(description="取得消息明细",
            detail="取得消息明细<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    public ResultData get(HttpServletRequest request) throws Exception {
        try{
            String id = RequestUtil.getString(request, "id");
            SysUser curUser = (SysUser) ContextUtil.getCurrentUser();
            MessageSend messageSend = sendService.getById(id);
            //当消息发送用户跟当前用户相同添加用户为已读
            if (messageSend != null && !messageSend.getUserId().equals(curUser.getUserId())) {
                messageReadService.addMessageRead(messageSend.getId(), curUser);
            }
            //发送接收者id及组织id到页面
            List<MessageReceiver> receivers = receiverService.getByMessageId(id);
            String receiverOrgId = "";
            String receiverId = "";
            String receiverOrgName="";
            for (int i = 0; i < receivers.size(); i++) {
                //确认是接收者是否为一个组织
                if (MessageReceiver.TYPE_ORG.equals(receivers.get(i).getReceiveType())) {
                    if (i == receivers.size() - 1) {
                        receiverOrgId = receiverOrgId + receivers.get(i).getReceiverId();
                        receiverOrgName=receiverOrgName+receivers.get(i).getReceiver();
                    } else {
                        receiverOrgId = receiverOrgId + receivers.get(i).getReceiverId() + ',';
                        receiverOrgName=receiverOrgName+receivers.get(i).getReceiver()+',';
                    }
                } else {
                    if (i == receivers.size() - 1) {
                        receiverId = receiverId + receivers.get(i).getReceiverId();
                    } else {
                        receiverId = receiverId + receivers.get(i).getReceiverId() + ',';
                    }
                }
            }
            messageSend.setReceiverId(receiverId);
            messageSend.setReceiverOrgId(receiverOrgId);
            messageSend.setReceiverOrgName(receiverOrgName);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", messageSend);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 取得已读消息列表明细
     * @param request
     * @return ResultData
     */
    @RequestMapping("/readDetail")
    @Action(description="获取已读消息列表",
            detail="获取已读消息列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    public ResultData readDetail(HttpServletRequest request) {
        try{
            String id = RequestUtil.getString(request, "id");
            // 获得已读此消息的人员
            List<MessageRead> readList = messageReadService.getReadByMsgId(id);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", readList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 取得回复消息列表明细
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/replyDetail")
    @Action(description="获取回复消息列表",
            detail="获取回复消息列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    public ResultData replyDetail(HttpServletRequest request) {
        try{
            String messageId = RequestUtil.getString(request, "messageId");
            // 获得回复此消息的信息
            List<MessageReply> replyList = replyService.getByMessageId(messageId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", replyList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }


    /*                                  页面跳转部分
     *******************************************************************************************************************/

    /**
     * 发送消息明细页面
     * @param request
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_GET)
    @Action(description = "明细页面页面跳转", exectype = "页面跳转日志")
    public String getList(HttpServletRequest request, Model model) {
        String id = RequestUtil.getString(request, "id");
        SysUser curUser = (SysUser) ContextUtil.getCurrentUser();
        String userId = curUser.getUserId();
        model.addAttribute("userId", userId);
        model.addAttribute("id", id);
        return "messageSend/getView";
    }

    /**
     * 发送消息页面
     * @param request
     * @param model
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/send")
    @Action(description = "发送消息页面页面跳转", exectype = "页面跳转日志",detail = "<#if success>编辑发送消息数据获取成功</#if>")
    public String send(HttpServletRequest request, Model model) {
        String returnUrl = RequestUtil.getPrePage(request);
        model.addAttribute("returnUrl", returnUrl);
        return "messageSend/send";
    }

    /**
     * 发送消息页面
     * @param request
     * @param model
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/sendView")
    @Action(description = "发送消息页面页面跳转", exectype = "页面跳转日志")
    public String sendView(HttpServletRequest request, Model model) {
        String returnUrl = RequestUtil.getPrePage(request);
        model.addAttribute("returnUrl", returnUrl);
        return "messageSend/sendView";
    }

    /**
     * 修改消息页面
     * @param request
     * @param model
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    @Action(description = "修改消息页面页面跳转", exectype = "页面跳转日志")
    public String edit(HttpServletRequest request, Model model) {
        String messageId = RequestUtil.getString(request, "messageId");
        if(StringUtil.isNotEmpty(messageId)) {
            MessageSend messageSend = sendService.getById(messageId);
            List<MessageReceiver> list = receiverService.getByMessageId(messageId);

            //获取接收人和接收组织
            String sendName = messageSend.getReceiverName();
            if(StringUtil.isNotEmpty(sendName)) {
                String[] names = sendName.split(",");
                StringBuffer userId = new StringBuffer();
                StringBuffer userName = new StringBuffer();
                StringBuffer orgId = new StringBuffer();
                StringBuffer orgName = new StringBuffer();
                for (MessageReceiver receiver : list) {
                    for (String name : names) {
                        if (receiver.getReceiver().equals(name)) {
                            if (receiver.getReceiveType().equals(MessageReceiver.TYPE_USER)) {
                                userId.append(receiver.getReceiverId() + ",");
                                userName.append(receiver.getReceiver() + ",");
                                continue;
                            } else if (receiver.getReceiveType().equals(MessageReceiver.TYPE_ORG)) {
                                orgId.append(receiver.getReceiverId() + ",");
                                orgName.append(receiver.getReceiver() + ",");
                                continue;
                            }
                        }
                    }
                }
                //接收人赋值
                if (userId.length()>0 && userName.length()>0) {
                    messageSend.setReceiverId(userId.substring(0, userId.length() - 1));
                    messageSend.setReceiverName(userName.substring(0, userName.length() - 1));
                }
                //接收组织赋值
                if (orgId.length()>0 && orgName.length()>0) {
                    messageSend.setReceiverOrgId(orgId.substring(0, orgId.length() - 1));
                    messageSend.setReceiverOrgName(orgName.substring(0, orgName.length() - 1));
                }
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            model.addAttribute("messageSend",messageSend);
        }
        return "messageSend/send";
    }

    /**
     * 回复详情页面
     * @param request
     * @param model
     * @return html文件前缀
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/replyList")
    @Action(description = "回复详情页面页面跳转", exectype = "页面跳转日志")
    public String replyList(HttpServletRequest request, Model model) {
        String id = RequestUtil.getString(request, "id");
        model.addAttribute("id", id);
        return "messageSend/replyList";
    }


    /**
     * 消息发送页面
     * @return html文件前缀
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/form")
    @Action(description = "发送消息首页页面跳转", exectype = "页面跳转日志")
    public String form() {
        return "messageSend/form";
    }
}
